package stream.ThreadSafe;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created on 2018/12/16.
 */
public class ThreadSafeSample {
    public int sharedState;
    public void nonSafeAction() {
        List<String> list = new ArrayList<>();
        while (sharedState < 100000) {
//            synchronized (this){
                int former = sharedState;
                int latter = ++sharedState;
                if (former != latter - 1) {
                    String msg = "Observed data race, former is " + former + ", " + "latter is " + latter+"\n";
//                    list.add(msg);
                    System.out.printf(msg);
                }
//            }
        }
        System.out.println(list);
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadSafeSample sample = new ThreadSafeSample();
        new ThreadLocal().set("1");
        Thread threadA = new Thread(){
            public void run(){
                sample.nonSafeAction();
                System.out.println(new ThreadLocal().get());
            }
        };

        System.out.println(new ThreadLocal().get());

        Thread threadB = new Thread(){
            public void run(){
                sample.nonSafeAction();
                System.out.println(new ThreadLocal().get());
            }
        };
        threadA.start();
        threadB.start();
//        Executors.newFixedThreadPool(1).submit(threadA).get();
//        Executors.newFixedThreadPool(1).submit(threadB).get();
        threadA.join();
        threadB.join();
//        threadA.start();
    }
}
